package com.ls.common;

/**
 * @author atom.hu
 * @version V1.0
 * @Package com.ls.common
 * @date 2021/10/13 19:21
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局的异常处理器
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
//@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> doSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){
        //1 打印异常信息：Duplicate entry 'zhangsan' for key 'idx_username'
        log.error(ex.getMessage());
        //2 判断异常信息内容
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            //xx用户名已存在
            return R.error(split[2]+"已存在");
        }
        return R.error("未知错误");
    }
}
